//
//  SWHomeViewModel.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/23.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit

class SWHomeGetDataViewModel: NSObject {
    

    var originalViewModelArr:[SWOriginalViewModel] = [SWOriginalViewModel]()
    


}

// MARK: - 加载首页网络数据
extension SWHomeGetDataViewModel{
    
    //这里需要把当前的刷新模式传进来,所以加了一个参数,而当前加载的消息条数需要传出去,所以放在了闭包的参数里面传出去
    func loadHomeData(isPullUp:Bool,isFinish:(isSuc:Bool,messageCount:Int)->()){
        
        var sinceID:Int64 = 0
        var maxID:Int64 = 0
        
        /*
        - 如果是上啦记载更多  需要给服务器maxid   sinceid == 0
        - 如果是下拉刷新  需要给服务器sinceId   maxId == 0
        - 如果sinceid == 0  maxid == 0  默认服务器返回最新的20条数据
        */
        //如果是上啦刷新
        if isPullUp{
            sinceID = 0
            maxID = originalViewModelArr.last?.homeModel?.id ?? 0
            
        }else{
            //如果是下拉刷新
            sinceID = originalViewModelArr.first?.homeModel?.id ?? 0
            maxID = 0
        }

        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let pragrams = [
            
            "access_token":SWUserAcountViewModel.sharedUserAcountViewModel.accesToken!,
            "since_id":"\(sinceID)",
            "max_id":"\(maxID)"
        ]
        
        NetWorkTools.sharedNetWorkTools.request(.Get, URLString: urlStr, parameters: pragrams) { (responseObject, error) -> () in
            
            //是否有值,是否是数组
            guard let res = responseObject?["statuses"] as? [[String:AnyObject]] else{
                
                isFinish(isSuc: false, messageCount: 0)
                print("res格式错误")
                return
            }
            
            //遍历数组 将字典转化成模型
            
            //定义数组时需要首先实例化
            var tempArr:[SWOriginalViewModel]? = [SWOriginalViewModel]()
            
            for dict in res{
                
                let homeModel = SWHomeModel(dict: dict)
           
                let originalViewModel = SWOriginalViewModel(homeModel: homeModel)
                
                tempArr?.append(originalViewModel)
        
            }
            //得到一个数组,里面全是originalViewModel,通知homeVC刷新tableView

            //上啦  将数据加到元数据的后面
            if isPullUp{
                self.originalViewModelArr = self.originalViewModelArr + tempArr!
                
                isFinish(isSuc: true, messageCount: -1)
                
            }else{
            //下拉 将新数组加到原数组的前面
                self.originalViewModelArr = tempArr! + self.originalViewModelArr
                
                isFinish(isSuc: true, messageCount: (tempArr?.count)!)
            }
            
          //  print("--------")
          //  print(tempArr?.count)
           // print(self.originalViewModelArr.count)
            
            
        
        }
        
        
        
        
        
    }
    
    
    
}
